package com.itheima.heimademo01.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.heimademo01.base.response.Result;
import com.itheima.heimademo01.base.utils.ThreadLocalUtil;
import com.itheima.heimademo01.mapper.ArticleMapper;
import com.itheima.heimademo01.pojo.dto.ArticleUpdateDTO;
import com.itheima.heimademo01.pojo.dto.PageBean;
import com.itheima.heimademo01.pojo.entity.Article;
import com.itheima.heimademo01.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;


    // 新增文章
    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleMapper.add(article);
    }


    // 文章列表(条件分页)
    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 创建PageBean对象
        PageBean<Article> pageBean = new PageBean();
        // 开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        // 调用mapper
        List<Article> as = articleMapper.list(userId, categoryId, state);
        Page<Article> p = (Page<Article>) as;
        pageBean.setTotal(p.getTotal());
        pageBean.setItems(p.getResult());
        return pageBean;
    }

    // 获取文章详情
    @Override
    public Article detail(Integer id) {
        Article article = articleMapper.detail(id);
        return article;
    }

    // 更新文章
    @Override
    public void update(ArticleUpdateDTO articleUpdateDTO) {
        articleMapper.update(articleUpdateDTO);
    }

    // 删除文章
    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

}
